/*
 * Copyright (c) Wondertek Technologies Co., Ltd. 2019-2020. All rights reserved.
 */
package com.wd.amodel.util;

import android.os.Handler;
import android.os.Looper;
import android.os.Message;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;


/**
 * <线程池工具类>
 *
 * @author ThreadUtils
 * @version [V1.0.0.0, 2020/4/7]
 * @since V1.0.0.0
 */
public final class ThreadUtils {
    /**
     * CPU 个数
     */
    private static final int CPU_COUNT = Runtime.getRuntime().availableProcessors();

    /**
     * 主线程 Handler
     */
    private static final Handler MAIN_HANDLER = new Handler(Looper.getMainLooper());

    /**
     * 线程池大小
     */
    private static final int POOL_SIZE = 2;

    /**
     * 普通的线程组池大小：1. （CPU个数 -1） 和 4 取最小值得到值 A 2. 值 A 和 2 取最大值，保证不低于两组
     */
    private static final int NORMAL_GROUP_POOL_SIZE = Math.max(2, Math.min(CPU_COUNT - 1, 4));

    /**
     * 创建线程池。线程池的"最大池大小"和"核心池大小"都为1(THREADS_SIZE)，"线程池"的阻塞队列容量为1(CAPACITY)。
     */
    private static final ThreadPoolExecutor POLL = new ThreadPoolExecutor(POOL_SIZE, POOL_SIZE, 20L,
            TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(1));

    private ThreadUtils() {
    }

    /**
     * 提交任务执行
     */
    public static void execute(Runnable runnable) {
        POLL.execute(runnable);
    }

    /**
     * 关闭线程池
     */
    public static void unInit(String poolName) {
        if (POLL == null || POLL.isShutdown()) {
            return;
        }
        POLL.shutdownNow();
    }

    public static void post(Runnable runnable) {
        MAIN_HANDLER.post(runnable);
    }

    public static void postDelay(Runnable runnable, long delayMillis) {
        MAIN_HANDLER.postDelayed(runnable, delayMillis);
    }

    public static void sendEmptyMessage(int what) {
        MAIN_HANDLER.sendEmptyMessage(what);
    }

    public static void sendEmptyMessageDelay(int what, long delay) {
        MAIN_HANDLER.sendEmptyMessageDelayed(what, delay);
    }

    public static void sendMessage(Message message) {
        MAIN_HANDLER.sendMessage(message);
    }

    public static void sendMessageDelay(Message message, long delay) {
        MAIN_HANDLER.sendMessageDelayed(message, delay);
    }

    public static void removeMessages(int message) {
        MAIN_HANDLER.removeMessages(message);
    }

    public static void removeCallbacks(Runnable callback) {
        MAIN_HANDLER.removeCallbacks(callback);
    }

}
